<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <!-- <el-form-item label="编号" prop="number">
              <el-input v-model="queryParams.number" placeholder="请输入编号" clearable @keyup.enter="handleQuery" />
            </el-form-item> -->
            <el-form-item label="到货时间" prop="arrivalTime" style="width: 308px">
              <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
                range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                style="width: 100%"></el-date-picker>
            </el-form-item>
            <el-form-item label="类别" prop="type">
              <el-select v-model="queryParams.type" placeholder="请选择使用类型" clearable>
                <el-option v-for="dict in item_apply_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="审批状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择审批状态" clearable>
                <el-option v-for="dict in approval_record_status" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间" prop="applyTime" style="width: 308px">
              <el-date-picker v-model="createTimeRange" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
                range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                style="width: 100%"></el-date-picker>
            </el-form-item>
            <el-form-item label="物品名称" prop="itemName">
                <el-input  v-model="queryParams.itemName" placeholder="请输入物品名称"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <template v-if="!hasFinalPermission">
            <el-col :span="1.5">
              <el-button type="primary" plain icon="Plus" @click="handleAdd"
                v-hasPermi="['system:admItemApply:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
                v-hasPermi="['system:admItemApply:edit']">修改</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
                v-hasPermi="['system:admItemApply:remove']">删除</el-button>
            </el-col>
          </template>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['system:admItemReturn:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="admItemApplyList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键id" align="center" prop="id" v-if="false" />
        <el-table-column label="申请人" align="center" prop="applyId">
          <template #default="scope">
            <span>{{ scope.row.applyName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="申请部门" align="center" prop="deptId">
          <template #default="scope">
            <el-tag type="primary" disable-transitions>
              {{ scope.row.deptName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="类别" align="center" prop="type">
          <template #default="scope" style="width: 100%; text-align: center;">
            <div class="flex flex-wrap gap-1 justify-center">
              <el-tag v-for="typeValue in Array.isArray(scope.row.type) ? scope.row.type : [scope.row.type]"
                :key="typeValue" type="primary" disable-transitions class="mb-1">
                {{ getTypeLabel(typeValue) }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="物品名称" align="center" prop="itemName">
          <template #default="scope">
            <el-tooltip :content="scope.row.itemName" placement="top" :disabled="!scope.row.itemName">
              <div style="width: 100%; text-align: center;">
                <span
                  style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                  {{ scope.row.itemName }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="品牌名称" align="center" prop="brandName">
          <template #default="scope">
            <el-tooltip :content="scope.row.brandName" placement="top" :disabled="!scope.row.brandName">
              <div style="width: 100%; text-align: center;">
                <span
                  style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                  {{ scope.row.brandName }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="规格型号" align="center" prop="specificationName">
          <template #default="scope">
            <el-tooltip :content="scope.row.specificationName" placement="top" :disabled="!scope.row.specificationName">
              <div style="width: 100%; text-align: center;">
                <span
                  style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                  {{ scope.row.specificationName }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="用品说明" align="center" prop="describe">
          <template #default="scope">
            <el-tooltip :content="scope.row.describe" placement="top" :disabled="!scope.row.describe">
              <div style="width: 100%; text-align: center;">
                <span
                  style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                  {{ scope.row.describe }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="数量" align="center" prop="amount" />
        <el-table-column label="单位" align="center" prop="unit" />
        <el-table-column label="单价" align="center" prop="price">
          <template #default="scope">
            <el-tooltip :content="scope.row.price" placement="top" :disabled="!scope.row.price">
              <div style="width: 100%; text-align: center;">
                <span
                  style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                  {{ scope.row.price }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="质量要求" align="center" prop="qualityRequirement">
          <template #default="scope">
            <el-tooltip :content="scope.row.qualityRequirement" placement="top"
              :disabled="!scope.row.qualityRequirement">
              <div style="width: 100%; text-align: center;">
                <span
                  style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                  {{ scope.row.qualityRequirement }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="到货时间" align="center" prop="arrivalTime" width="100">
          <template #default="scope">
            <span>{{ parseTime(scope.row.arrivalTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="审批状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="approval_record_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="申请时间" align="center" prop="applyTime" width="100">
          <template #default="scope">
            <span>{{ parseTime(scope.row.applyTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark">
          <template #default="scope">
            <el-tooltip :content="scope.row.remark" placement="top" :disabled="!scope.row.remark">
              <div style="width: 100%; text-align: center;">
                <span
                  style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                  {{ scope.row.remark }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="110">
          <template #default="scope">
            <template v-if="!hasFinalPermission">
              <el-tooltip content="修改" placement="top">
                <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                  v-hasPermi="['system:admItemApply:edit']"></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                  v-hasPermi="['system:admItemApply:remove']"></el-button>
              </el-tooltip>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <apply-form v-model:visible="dialog.visible" :title="dialog.title" @success="handleUpdate" ref="applyFormRef" />
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 导入对话框 -->
    <el-dialog v-model="upload.open" :title="upload.title" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
        :disabled="upload.isUploading" :http-request="handleUploadRequest" :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess" :auto-upload="false" drag>
        <el-icon class="el-icon--upload">
          <UploadFilled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="text-center el-upload__tip">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
              @click="handleImportTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="AdmItemApply" lang="ts">
import { listAdmItemApply, getAdmItemApply, delAdmItemApply, importItems } from '@/api/general/administration/item/apply';
import { AdmItemApplyVO, AdmItemApplyQuery, AdmItemApplyForm } from '@/api/general/administration/item/apply/types';
import ApplyForm from './ApplyForm.vue';
import { useUserStore } from '@/store/modules/user';
import { globalHeaders } from '@/utils/request';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
// 引入数据字典
const { approval_record_status, item_apply_type } = toRefs<any>(proxy?.useDict('approval_record_status', 'item_apply_type'));

const dialogVisible = ref(false);
const auditMode = ref(false);
const formData = ref<AdmItemApplyVO>({} as AdmItemApplyVO);
const auditList = ref([{ auditor: '', status: '', comment: '' }]);

const admItemApplyList = ref<AdmItemApplyVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const applyFormRef = ref();

const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const createTimeRange = ref<[DateModelType, DateModelType]>(['', '']);

// 用户信息
const userStore = useUserStore();

// 导入相关
const uploadRef = ref();
const upload = reactive({
  // 是否显示弹出层
  open: false,
  // 弹出层标题
  title: '',
  // 是否禁用上传
  isUploading: false,

  // 设置上传的请求头部
  headers: globalHeaders(),
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/pro/info/importData'
});


const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: AdmItemApplyForm = {
  id: undefined,
  applyId: undefined,
  deptId: undefined,
  type: undefined,
  itemName: undefined,
  brandName: undefined,
  specificationName: undefined,
  describe: undefined,
  amount: undefined,
  unit: undefined,
  price: undefined,
  qualityRequirement: undefined,
  arrivalTime: undefined,
  status: undefined,
  applyTime: undefined,
  remark: undefined,
}
const data = reactive<{
  queryParams: {
    pageNum: number;
    pageSize: number;
    number?: string;
    deptId?: string | number;
    type?: number;
    status?: number;
    itemName?: string;
    params: {
      bUseTime?: string; // 使用开始时间
      eUseTime?: string; // 使用结束时间
      beginTime?: string; // 创建开始时间
      endTime?: string; // 创建结束时间
    };
  };
}>({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    number: undefined,
    deptId: undefined,
    type: undefined,
    status: undefined,
    params: {
      bUseTime: undefined,
      eUseTime: undefined,
      beginTime: undefined,
      endTime: undefined
    }
  }
});

const { queryParams } = toRefs(data);

/** 查询物资采购申请列表 */
const getList = async () => {
  loading.value = true;
  try {
    const params = { ...queryParams.value };
    if (dateRange.value?.length === 2) {
      params.params = {
        ...params.params,
        bUseTime: dateRange.value[0]?.toString(),
        eUseTime: dateRange.value[1]?.toString()
      };
    }
    if (createTimeRange.value?.length === 2) {
      params.params = {
        ...params.params,
        beginTime: createTimeRange.value[0]?.toString(),
        endTime: createTimeRange.value[1]?.toString()
      };
    }
    const res = await listAdmItemApply(params);
    admItemApplyList.value = res.rows;
    total.value = res.total;
  } catch (error) {
    console.error('获取列表失败:', error);
    proxy?.$modal.msgError('获取列表失败');
  } finally {
    loading.value = false;
  }
};

// 获取物品类别
const getTypeLabel = (value: string | number) => {
  const dict = item_apply_type.value; // [{label: '类型1', value: '0'}, ...]
  const item = dict.find(d => d.value == value);
  return item ? item.label : value;
};

const hasFinalPermission = computed(() => {
  const permissions = useUserStore().permissions;
  return permissions.includes('administration:seal:final');
});


/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  createTimeRange.value = ['', ''];
  queryFormRef.value?.resetFields();
  queryParams.value.params = {
    bUseTime: undefined,
    eUseTime: undefined,
    beginTime: undefined,
    endTime: undefined
  };
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: AdmItemApplyVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  applyFormRef.value?.reset();
  dialog.visible = true;
  dialog.title = "物资采购申请";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: AdmItemApplyVO) => {
  console.log(row);
  const _id = row?.id || ids.value[0];
  if (row.status != 0) {
    ElMessage.error("只能对未审核的申请进行修改")
  } else {
    try {
      const res = await getAdmItemApply(_id);
      applyFormRef.value.openDialog(res.data, false);
      dialog.visible = true;
      dialog.title = '修改物资采购申请';
    } catch (error) {
      console.error('获取详情失败:', error);
      proxy?.$modal.msgError('获取详情失败');
    }
  }
}

/** 删除按钮操作 */
const handleDelete = async (row?: AdmItemApplyVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除物资采购申请编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delAdmItemApply(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/**
 * 下载导入模板
 */
const handleImportTemplate = () => {
  proxy?.download(
    '/system/admItemApply/downloadTemplate',
    {},
    `book_store_template_${Date.now()}.xlsx`
  );
};

const handleUploadRequest = async (option: any) => {
  if (!option.file) return;
  try {
    upload.isUploading = true;
    const form = {
      deptId: userStore.deptId,
      storeId: userStore.userId
    }

    // 调用你的接口
    await importItems(option.file, form);

    ElMessage.success('导入成功');
    getList(); // 刷新列表
    option.onSuccess?.({ msg: '导入成功' }, option.file);
  } catch (err: any) {
    ElMessage.error(err?.message || '导入失败');
    option.onError?.(err);
  } finally {
    upload.isUploading = false;
    uploadRef.value?.clearFiles();
    upload.open = false;
  }
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('system/admItemApply/export', {
    ...queryParams.value
  }, `admItemApply_${new Date().getTime()}.xlsx`)
}



// 处理更多命令
const handleMoreCommand = (command: string) => {
  switch (command) {
    case 'download-template':
      handleImportTemplate();
      break;
    case 'import-data':
      upload.open = true; // 打开上传弹窗
      upload.title = '导入物品';
      break;
    case 'export-data':
      handleExport();
      break;
    default:
      break;
  }
};

/**
 * 提交上传文件
 */
const submitFileForm = () => {
  uploadRef.value?.submit();
};

/**
 * 文件上传中处理
 */
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};

/**
 * 文件上传成功处理
 */
const handleFileSuccess = (response: any) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value?.clearFiles();

  // 导出结果弹出
  ElMessageBox.alert(response.msg, '导入结果', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '确定',
    type: 'info'
  });
  // 重新获取列表
  getList();
};

/** 部门审核按钮操作 */
const handleAudit = (row: AdmItemApplyVO) => {
  dialog.title = '部门审核';
  applyFormRef.value.openDialog(row, true); // 审核模式
  dialog.visible = true;
};

onMounted(() => {
  getList();
});
</script>
